<!-- 租户管理 -->
<template>
  <div class="user-manage">
    <!-- 新增、搜索 -->
    <div class="search">
      <el-button type="primary" @click="onShowTenantDrawer(null, 'CREATE')" class="add-user-btn">新增租户</el-button>
      <search placeholder="请输入租户名称" :live-search="true" :search-word.sync="tenantName" @search="onSearch"/>
    </div>
    <!-- 租户列表 -->
    <div class="users-table">
      <el-table :data="tableData" stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="userName" label="租户"></el-table-column>
        <el-table-column label="租户状态">
          <template slot-scope="scope">
            <span>{{ getUserStatus(scope) }}</span>
            <el-divider direction="vertical"></el-divider>
            <el-button type="primary" size="small" @click="onClickUserStatus(scope)" class="lock-btn" plain>{{ scope.row.isLock == '0' ? '锁定': '解锁' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="租户描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip content="租户详情" placement="top">
              <el-button type="text" @click="onShowDetail(scope)" class="btn-icon-box">
                <i class="el-icon-view opt-icon"></i>
              </el-button>
            </el-tooltip>
            <el-divider direction="vertical"></el-divider>
            <el-tooltip content="编辑租户" placement="top">
              <el-button type="text" @click="onShowTenantDrawer(scope, 'UPDATE')" class="btn-icon-box">
                <i class="el-icon-edit opt-icon"></i>
              </el-button>
            </el-tooltip>
            <el-divider direction="vertical"></el-divider>
            <el-tooltip content="配置资源" placement="top">
              <el-button type="text" @click="onShowTenantDrawer(scope, 'RESOURCE')" class="btn-icon-box">
                <i class="el-icon-set-up opt-icon"></i>
              </el-button>
            </el-tooltip>
            <el-divider direction="vertical"></el-divider>
            <el-tooltip content="修改密码" placement="top">
              <el-button type="text" @click="onShowPwdDialog(scope)" class="btn-icon-box">
                <i class="el-icon-key opt-icon"></i>
              </el-button>
            </el-tooltip>
            <el-divider direction="vertical"></el-divider>
            <el-tooltip content="下载 keytab" placement="top">
              <el-button type="text" @click="onDownloadKeytab(scope)" class="btn-icon-box">
                <i class="el-icon-download opt-icon"></i>
              </el-button>
            </el-tooltip>
            <el-divider direction="vertical"></el-divider>
            <el-tooltip content="删除租户" placement="top">
              <el-button type="text" @click="onShowDeleteDialog(scope)" class="btn-icon-box">
                <i class="el-icon-delete opt-icon"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <pagination 
        :total="tenantNum"
        :current-page="currentPage"
        :page-size="pageSize"
        @currentPageChange="handleCurrentChange"
        @pageSizeChange="handlePageSizeChange"
    />
    <!-- 租户表单（抽屉） -->
    <tenant-drawer 
      v-if="tenantDrawerStatus"
      :drawerStatus="tenantDrawerStatus" 
      :tenantForm="tenantForm" 
      :reloadCurPage.sync="reloadCurPage"
      @updateDrawer="updateDrawer" 
      @changeStatus="onChangeDrawerStatus" 
    />
    <!-- 租户详情（对话框） -->
    <person-detail 
      titleTxt="租户详情"
      v-if="showDetail" 
      :visible.sync="showDetail" 
      :person="detailObj" 
      @cleanData="cleanDetailObj"
    />
    <!-- 修改密码（对话框） -->
    <el-dialog title="修改密码" class="change-pwd-dialog" :visible.sync="showPwdDialog" :before-close="onClosePwdDialog">
      <span slot="title">修改租户 {{tenantForm.userName}} 密码</span>
      <el-form :model="tenantForm" :rules="tenantFormRules" ref="tenantForm" label-width="120px">
        <el-form-item label="新密码" prop="tenantPwd">
          <el-input v-model="tenantForm.tenantPwd" autocomplete="off" autofocus show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="tenantVerifyPwd">
          <el-input v-model="tenantForm.tenantVerifyPwd" autocomplete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClosePwdDialog">取 消</el-button>
        <el-button type="primary" @click="onSubmitPwd" :loading="pwdLoading">{{ pwdLoading ? '提交中 ...' : '确 定' }}</el-button>
      </div>
    </el-dialog>
    <!-- 删除租户（对话框） -->
    <el-dialog
      title="确认删除"
      :visible.sync="showDeleteDialog"
      :before-close="handleClose" 
      width="30%">
      <span slot="title">删除租户 {{tenantForm.userName}}</span>
      <label>是否保留数据：</label>
      <el-switch v-model="preserveData" active-text="是" inactive-text="否" :disabled="delLoading"></el-switch>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCloseDeleteDialog">取 消</el-button>
        <el-button type="primary" @click="onDeleteTenant" :loading="delLoading">{{ delLoading ? '提交中 ...' : '确 定' }}</el-button>
      </span>
    </el-dialog>
    <!-- 确认弹框 -->
    <confirm 
      :title="confirmTitle" 
      :showConfirm="showConfirm" 
      @closeConfirm="closeConfirm" 
      @submitConfirm="submitLockOrUnlock"
    />
  </div>
</template>
<script>
import _ from 'lodash';
import { mapState } from 'vuex';
import { Message } from 'element-ui';
import { managerApi } from '@/request';
import { downloadKeytab, validatePwdForElementUI, validateVerifyPwdForElementUI, validateSearchName, resetForm } from '@/utils';
import { USER_LOCK_MAP, SERVICE_OPTIONS, CAPACITY_UNIT_MAP, DEFAULT_PAGE_SIZE } from '@/const';
import confirm from '@/components/manager/Confirm';
import tenantDrawer from "@/components/manager/TenantDrawer";
import personDetail from "@/components/manager/PersonDetail";
import Pagination from '@/components/common/Pagination.vue';
import Search from '@/components/common/Search';

export default {
  components: { tenantDrawer, personDetail, confirm, Search, Pagination },
  data() {
    const validateVerifyPwd = (rule, value, callback) => {
        validateVerifyPwdForElementUI(value, this.tenantForm.tenantPwd, callback);
    };
    return {
      tenantName: '', // 查询
      searchWarning: false,
      tenantNum: 0, // 列表项总条数
      currentPage: 1, // 当前页数
      pageSize: DEFAULT_PAGE_SIZE, // 每页列表项数
      tableData: [], // 租户列表
      loading: false,
      reloadCurPage: true, // 操作后返回列表，拉取的分页idx
      tenantDrawerStatus: null, // 'CREATE'/'UPDATE'/'RESOURCE'/null  租户表单状态
      showDetail: false, // 展示租户详情
      showConfirm: false, // 展示解锁/锁定确认框
      confirmTitle: '', // 解锁确认框标题
      showPwdDialog: false, // 展示修改密码框
      showDeleteDialog: false, // 展示删除框
      preserveData: true, // 是否保留数据
      pwdLoading: false,
      delLoading: false,
      detailObj: { id: '', type: '', name: '', description: '', isLock: ''}, // 详情内容
      tenantForm: { // 租户表单
        userId: '',
        userName: '',
        description: '',
        isLock: '',
        tenantPwd: '',
        tenantVerifyPwd: ''
      },
      tenantFormRules: { // 修改密码表单校验
        tenantPwd: [{ required: true, validator: validatePwdForElementUI, trigger: 'blur' }],
        tenantVerifyPwd: [{ required: true, validator: validateVerifyPwd, trigger: 'blur' }]
      }
    };
  },
  computed: {
    hasData() {
      return this.tenantNum > 0;
    },
    showTenantDrawer: {
      get() {
        return !!this.tenantDrawerStatus;
      },
      set(val) {
        this.tenantDrawerStatus = null;
        this.cleanTenantForm();
      }
    }
  },
  mounted() {
    this.getTenantList({pageIndex: this.currentPage, pageSize: 10, isTenantGetTen: '0'});
  },
  methods: {
    getTenantList(param = {pageIndex: 1, pageSize: 10, isTenantGetTen: '0'}) { // 拉取租户列表
      this.loading = true;
      managerApi.getTenantList(param).then((res) => {
        this.loading = false;
        this.tableData =  _.get(res, 'pageList', []);
        this.tenantNum = _.get(res, 'count', 0);
        this.currentPage = param.pageIndex; // 同步列表分页
      }).catch(err => {
        this.loading = false;
      })
    },
    setTenantForm(scope) { // 设置租户表单(租户与用户 共用一个接口)
      let tenantId = scope.row['userId']; // 列表中当前行的 userId
      let curTenant = (this.tableData.filter((item, idx) => {
        return item.userId == tenantId;
      }) || [])[0];
      if (curTenant) {
        this.tenantForm.userName = curTenant.userName;
        this.tenantForm.userId = curTenant.userId;
        this.tenantForm.description = curTenant.description;
        this.tenantForm.isLock = curTenant.isLock;
      }
    },
    cleanTenantForm() { // 清除租户表单
      this.tenantForm = { userId: '', userName: '', description: '', tenantPwd: '', tenantVerifyPwd: '', isLock: '' };
    },

    /* 锁定/解锁租户start */
    getUserStatus(scope) { // 列表展示“租户状态”转换
      let isLock = scope.row['isLock'];
      return USER_LOCK_MAP[isLock];
    },
    onClickUserStatus(scope) {
     this.showConfirm = true;
     this.setTenantForm(scope);
     let txt = {
       status: scope.row.isLock == '0' ? '锁定' : '解锁',
       name: scope.row.userName
     };
     this.confirmTitle = `您是否确认${txt.status}租户 ${txt.name} ？`;
    },
    closeConfirm() { // 更新confirm展示状态
      this.showConfirm = false;
      this.confirmTitle = '';
      this.cleanTenantForm();
    },
    submitLockOrUnlock() { // 锁定/解锁租户
      let tenant = this.tenantForm;
      let user = {
        type: tenant.isLock, // 锁定用户，type为'0'；解锁用户，type为'1'
        userId: tenant.userId
      };
      let text = tenant.isLock == '0' ? '已锁定' : '已解锁';
      managerApi.unlockUser(user).then(res => {
        this.closeConfirm();
        Message.success(`租户 ${tenant.userName} ${text}`);
        this.getTenantList({pageIndex: 1, pageSize: 10, userName: this.tenantName, isTenantGetTen: '0' });
      }).catch(err => {
        this.closeConfirm();
      })
    },
    /* 锁定/解锁租户end */

    /* 详情start */
    onShowDetail(scope) {
      this.showDetail = true;
      // 设置租户信息
      this.detailObj.type = 'TENANT';
      this.detailObj.id = scope.row.userId;
      this.detailObj.name = scope.row.userName;
      this.detailObj.isLock = scope.row.isLock;
      this.detailObj.description = scope.row.description;
    },
    cleanDetailObj() {
      this.detailObj = { id: '', type: '', name: '', description: '', isLock: ''};
    },
    /* 详情end */

    /* 租户表单start */
    onShowTenantDrawer(scope, status) { // 租户表单 抽屉
      if (status === 'UPDATE' || status === 'RESOURCE') {
        this.setTenantForm(scope);
      }
      this.tenantDrawerStatus = status;
    },
    updateDrawer(val) { // 更新抽屉的展开状态（子组件触发）
      this.tenantDrawerStatus = val; // 置为false
      this.cleanTenantForm(); // 关闭drawer后，清除tenantForm
      // 关闭drawer的时候，拉取列表的index如何处理？创建，更新->首页，取消->当前页
      this.getTenantList({pageIndex: this.reloadCurPage ? this.currentPage : 1, pageSize: 10, userName: this.tenantName, isTenantGetTen: '0'});
    },
    onChangeDrawerStatus(status) {
      // status 关联drawer的tab页：(tab的 activeName 关联至status)
      // 创建租户时，为tab1（first），status == 'create';
      // 编辑租户时，为tab1（first），status == 'update';
      // 分配资源时，为tab2（second），status == 'resource';
      this.tenantDrawerStatus = status;
    },
    /* 租户表单end */

    /* 修改密码start */
    onShowPwdDialog(scope) { // 修改租户密码
      this.setTenantForm(scope);
      this.showPwdDialog = true;
    },
    onClosePwdDialog() {
      this.showPwdDialog = false;
      this.cleanTenantForm();
      resetForm(this.$refs['tenantForm']);
    },
    onSubmitPwd() { // 提交新密码
      this.$refs['tenantForm'].validate((valid) => {
        if (valid) {
          let tenant = {
            userId: this.tenantForm.userId,
            newPassword: this.tenantForm.tenantPwd
          };
          this.pwdLoading = true;
          managerApi.changeTenantPwd(tenant).then((res) => {
            this.pwdLoading = false;
            this.onClosePwdDialog();
            Message.success("密码修改成功");
            this.getTenantList({pageIndex: 1, pageSize: 10, userName: this.tenantName, isTenantGetTen: '0'});
          }).catch(err => {
            this.pwdLoading = false;
          })
        } else {
          return false;
        }
      });
    },
    /* 修改密码end */

    onDownloadKeytab(scope) { // 下载keytab
      downloadKeytab(scope.row.userId);
    },

    /* 删除租户start */
    onShowDeleteDialog(scope) { // 删除租户
      this.setTenantForm(scope);
      this.showDeleteDialog = true;
    },
    onCloseDeleteDialog() {
      this.showDeleteDialog = false;
      this.preserveData = true; // 关闭删除框，preserveData初始化为默认值
      this.cleanTenantForm();
    },
    onDeleteTenant() { // 确认删除租户，提交后台（是否保留数据）
      let tenant = { 
        userId: this.tenantForm.userId,
        isDelResource: this.preserveData ? 0 : 1 // 0-保留，1-删除
      };
      this.delLoading = true;
      managerApi.deleteTenant(tenant).then((res) => {
        this.delLoading = false;
        this.onCloseDeleteDialog();
        Message.success("租户删除成功");
        this.preserveData = true;
        this.getTenantList({pageIndex: this.currentPage, pageSize: 10, userName: this.tenantName, isTenantGetTen: '0'});
      }).catch(err => {
        this.delLoading = false;
        // res.code = 2（租户删除成功，部分资源删除失败） 时，展示res.msg
        Message.error(err.msg);
      })
    },
    /* 删除租户end */

    handleClose(done) {
      this.preserveData = true; // 关闭删除框，preserveData初始化为默认值
      done();
    },
    onSearch() {
      // validateSearchName(this.tenantName) && 
      this.getTenantList({pageIndex: 1, pageSize: this.pageSize, userName: this.tenantName, isTenantGetTen: '0'});
    },
    handleCurrentChange(val) { // 分页
      this.currentPage = val;
      this.getTenantList({pageIndex: val, pageSize: this.pageSize, userName: this.tenantName, isTenantGetTen: '0'});
    },
    // pageSize变化的回调
    handlePageSizeChange(pageSize) {
        let param = { 
            pageIndex: 1, 
            pageSize, 
            isTenantGetTen: '0'
        }
        if (this.tenantName) {
            param.userName = this.tenantName
        }
        this.pageSize = pageSize;
        this.getTenantList(param)
    },
  }
};
</script>
<style scoped lang="scss">
@import '~@/styles/userListCommon.scss';
</style>
<style lang="scss">
/* 修改密码 */
.change-pwd-dialog .el-dialog {
  width: 520px;
  .el-input {
    width: 300px;
  }
}
</style>
